package com.hizt.mmb.sms.service.impl;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.hizt.mmb.sms.properties.SmsProperties;
import com.hizt.mmb.sms.service.SmsService;
import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.aliyun.teautil.Common.toJSONString;

/**
 * 作者：李嘉浩
 * 时间：2024-08-29-16:42
 * 功能：
 */

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void send(String phone) throws Exception {

        Config config = new Config()
                // 配置 AccessKey ID
                .setAccessKeyId(SmsProperties.KEY_ID)
                // 配置 AccessKey Secret
                .setAccessKeySecret(SmsProperties.KEY_SECRET);

        // 配置 Endpoint
        config.endpoint = SmsProperties.ENDPOINT;

        Client client = new Client(config);

        String code= RandomUtil.randomNumbers(6);
        //将验证码存入redis中
        stringRedisTemplate.opsForValue().set("service-sms"+phone,code,5, TimeUnit.HOURS);
        Map<String,String> map=new HashMap<>();
        map.put("code",code);

        // 构造请求对象，请填入请求参数值
        String signName = SmsProperties.SIGN_NAME;
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(signName)
                .setTemplateCode(SmsProperties.TEMPLATE_CODE)
                .setTemplateParam(JSONUtil.toJsonStr(map));

        // 获取响应对象
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

        // 响应包含服务端响应的 body 和 headers
        System.out.println(toJSONString(sendSmsResponse));


    }
}
